package com.eostoken.eos_wallet.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseActivity;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.PhotoUtils;
import com.fredy.mvp.BasePresenter;
import com.fredy.mvp.BaseView;
import com.fredy.mvp.Model;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.io.FileNotFoundException;
import java.io.InputStream;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;


public class QrcodeScanActivity extends BaseActivity implements QRCodeView.Delegate {

    @BindView(R.id.zxingview)
    ZXingView mZXingView;
    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    /**
     * 选择照片请求码
     */
    private static final int GET_PIC_CODE = 1001;
    private static final int CAMERA_REQUEST_CODE = 2;//请求码


    private boolean isOpen = false;
    private boolean isToWeb = false;
    private ProgressDialog mProgress;
    private Bitmap scanBitmap;
    private PhotoUtils photoUtils;

    @Override
    public int getContentView() {
        return R.layout.activity_qrcode;
    }

    @Override
    protected void initData() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(this, false);
        photoUtils = new PhotoUtils();
        photoUtils.setPhotoPathListener(new PhotoUtils.PhotoPathListener() {
            @Override
            public void getPathSuccess(String path) {
                LogUtils.dTag("QrcodeScanActivity==", "path = " + path);
                mZXingView.decodeQRCode(path);
            }
        });
    }

    @Override
    public void initView() {
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        initTopBar();
        mZXingView.setDelegate(this);
    }

    private void initTopBar() {
        mTopBar.setTitle(StringUtils.getString(R.string.str_qrcode_scan));
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mTopBar.addRightTextButton(StringUtils.getString(R.string.str_photo), R.id.topbar_right_change_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoUtils.albumSelect(QrcodeScanActivity.this);
            }
        });
    }


    @Override
    public void onScanQRCodeSuccess(String result) {
        LogUtils.dTag("QrcodeScanActivity==", "result = " + result);
        if (!ObjectUtils.isEmpty(result)) {
            scanQRCodeResult(result.trim());
        }
    }

    private void scanQRCodeResult(String result) {
        LogUtils.dTag("onScanQRCodeSuccess==", "result = " + result);
        vibrate();
        Intent intent = null;
        intent = new Intent();
        intent.putExtra(Constants.INTENT_EXTRA_KEY_QR_SCAN, result);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 手机振动
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        LogUtils.dTag("onCameraAmbientBrightnessChanged==1111==", "isDark " + isDark);
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        LogUtils.e("打开相机出错");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == GET_PIC_CODE) {
            try {
                final Uri imageUri = data.getData();
                InputStream imageStream = getContentResolver().openInputStream(imageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
//                mZXingView.decodeQRCode(bitmap);

                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(Void... params) {
                        return QRCodeDecoder.syncDecodeQRCode(bitmap);
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        scanQRCodeResult(result);
                    }
                }.execute();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 打开后置摄像头开始预览，但是并未开始识别
        mZXingView.startCamera();

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并且延迟0.1秒后开始识别
    }

    @Override
    protected void onStop() {
        // 关闭摄像头预览，并且隐藏扫描框
        mZXingView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mZXingView.onDestroy(); // 销毁二维码扫描控件
    }

    @Override
    public Model createModel() {
        return null;
    }

    @Override
    public BaseView createView() {
        return null;
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public boolean isShowState() {
        return true;
    }
}
